package com.sinba.common.system.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.sinba.common.dto.PageDTO;
import com.sinba.common.system.dao.IIMessageDAO;
import com.sinba.common.system.dto.IMessageDTO;
import com.sinba.common.system.entity.IMessage;
import com.sinba.common.user.dao.IRegisterUserDAO;
import com.sinba.common.user.entity.RegisterUser;

public class IMessageService implements IIMessageService {
	@Autowired
	private IIMessageDAO imessageDAO;
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	
	/**
	 * 分页查询
	 */
	@Transactional
	public PageDTO findPageIMessage(IMessageDTO dto , String sord, String sidx) {
		PageDTO pageDto = imessageDAO.findPageIMessage(dto, sord, sidx);
		List<IMessageDTO> list = new ArrayList<IMessageDTO>(pageDto.getData().size());
		List<IMessage> data = (List<IMessage>)pageDto.getData();
		for(IMessage entity : data){
			IMessageDTO imessageDto = new IMessageDTO();
			IMessageDTO.entity2dto(entity, imessageDto);
			
			RegisterUser user1 = registerUserDAO.findUniqueBy("loginName", entity.getSendUser());
			if(user1!=null){
				imessageDto.setSendUserName(user1.getUserName());
			}
			
			RegisterUser user2 = registerUserDAO.findUniqueBy("loginName", entity.getReceiveUser());
			if(user2!=null){
				imessageDto.setSendUserName(user2.getUserName());
			}
			
			list.add(imessageDto);
		}
		pageDto.setData(list);
		return pageDto;
	}
	
	/**
	 * 发送消息
	 */
	public void sendMessage(IMessageDTO messageDto) {
		IMessage entity = new IMessage();
		IMessageDTO.dto2entity(messageDto, entity);
		entity.setStatus("未读");
		entity.setSendDate(new Date());
		imessageDAO.save(entity);
	}

	
	/**
	 * 回复
	 */
	public void reply(IMessageDTO messageDto) {
		IMessage entity = new IMessage();
		IMessageDTO.dto2entity(messageDto, entity);
		entity.setSendDate(new Date());
		entity.setStatus("未读");
		imessageDAO.save(entity);
	}

	/**
	 * 删除
	 */
	public void deletes(Long[] ids) {
		// TODO Auto-generated method stub
		imessageDAO.deleteByIds(ids);
	}
	
	/**
	 * 状态变更
	 * @param messageDto
	 */
	public void changeStatus(IMessageDTO messageDto){
		IMessage entity = imessageDAO.findById(messageDto.getImId());
		entity.setStatus(messageDto.getStatus());
		imessageDAO.merge(entity);
	}
	

}
